package com.heima.wemedia.filter;

import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.pojos.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Order(1)
@WebFilter(filterName = "wmTokenFilter",urlPatterns = "/")
@Slf4j
@Component //扫描包，将实体类包加入到IOC容器中
public class WmTokenFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.获得请求响应消息
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //2.从请求中获取请求头,从请求头中获取id值
        String wmUserId = request.getHeader("userId");
        //3，判断id为不为空，将id赋值给threadLocal
        if (wmUserId != null){
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(wmUserId));
            WmThreadLocalUtils.setUserId(wmUser);
        }
        //没有id直接放行
        filterChain.doFilter(request,response);
        //处理器结束完清空用户信息
        WmThreadLocalUtils.clearWmUser();
    }
}
